package com.three.iot.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.three.iot.api.UserDeviceService;
import com.three.iot.api.UserService;
import com.three.iot.commons.dto.UserCondDto;
import com.three.iot.commons.dto.UserCreateDto;
import com.three.iot.commons.dto.UserResultDto;
import com.three.iot.commons.dto.UserUpdateDto;
import com.three.iot.commons.enums.IfAdminEnum;
import com.three.iot.commons.enums.Result;
import com.three.iot.commons.enums.ResultCode;
import com.three.iot.commons.enums.StatusEnum;
import com.three.iot.commons.utils.DateUtil;
import com.three.iot.commons.utils.ThreeDESUtil;
import com.three.iot.commons.dto.UserDeviceRespDto;
import com.three.iot.jdbc.mapper.SysUserMapper;
import com.three.iot.jdbc.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserDeviceService userDeviceService;
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Override
    public Page<UserResultDto> findUserPage(UserCondDto userCondDto) {
        //使用PageHelper类进行分页
        PageHelper.startPage(userCondDto.getPageNum(), userCondDto.getPageSize());
        Page<SysUser> sysUserPage = (Page) findList(userCondDto);
        Page<UserResultDto> topicResultDtoPage = convertDto(sysUserPage);
        return topicResultDtoPage;
    }

    @Override
    public Result<UserResultDto> findByUniqIndex(String uniqIndexNo) {
        SysUser sysUser = sysUserMapper.selectByIndex(uniqIndexNo);
        if (sysUser == null) {
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        UserResultDto userResultDto = buildSingleDto(sysUser);
        return Result.newSuccess(userResultDto);
    }

    @Override
    public Result createUser(UserCreateDto userCreateDto) {
        SysUser sysUser = sysUserMapper.selectByIndex(userCreateDto.getUserNo());
        SysUser sysUser1 = sysUserMapper.selectByIndex(userCreateDto.getNickName());
        SysUser sysUser2 = sysUserMapper.selectByIndex(userCreateDto.getEmailAddr());
        if (sysUser != null || sysUser1 != null|| sysUser2 != null) {
            return Result.newError(ResultCode.COMMON_DATA_EXISTS);
        }
        SysUser sysUser3 = new SysUser();
        BeanUtils.copyProperties(userCreateDto, sysUser3);
        sysUser3.setIfAdmin(Integer.valueOf(userCreateDto.getIfAdmin()==null?IfAdminEnum.NO.getCode():IfAdminEnum.YES.getCode()));
        String signPass1 = ThreeDESUtil.encryptToHex(userCreateDto.getLoginPass());
        sysUser3.setLoginPass(signPass1);
        sysUser3.setCreateNo(userCreateDto.getOperNo());
        sysUser3.setCreateTime(new Date());
        sysUser3.setModiNo(userCreateDto.getOperNo());
        sysUser3.setModiTime(new Date());
        sysUserMapper.insertSelective(sysUser3);
        //绑定设备
        userDeviceService.bindUserDeviceList(sysUser3.getUserNo(),userCreateDto.getIotIdList());
        return Result.newSuccess();
    }

    @Override
    public Result update(UserUpdateDto userUpdateDto) {
       /* SysUser sysUser1 = sysUserMapper.selectByIndex(userUpdateDto.getUserNo());
        SysUser sysUser2 = sysUserMapper.selectByIndex(userUpdateDto.getNickName());
        SysUser sysUser3 = sysUserMapper.selectByIndex(userUpdateDto.getEmailAddr());
        Integer updateId=Integer.valueOf(userUpdateDto.getId());
        if (sysUser1 != null || sysUser2 != null|| sysUser3 != null) {
            if(!sysUser1.getId().equals(updateId) || !sysUser2.getId().equals(updateId)|| !sysUser3.getId().equals(updateId)){
                return Result.newError(ResultCode.COMMON_DATA_EXISTS);
            }
        }*/
        SysUser sysUser = new SysUser();
        sysUser.setId(Integer.valueOf(userUpdateDto.getId()));
        BeanUtils.copyProperties(userUpdateDto, sysUser);
        sysUser.setIfAdmin(Integer.valueOf(userUpdateDto.getIfAdmin()==null?IfAdminEnum.NO.getCode():IfAdminEnum.YES.getCode()));
        String signPass1 = ThreeDESUtil.encryptToHex(userUpdateDto.getLoginPass());
        sysUser.setLoginPass(signPass1);
        sysUser.setModiNo(userUpdateDto.getOperNo());
        sysUser.setModiTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        //绑定设备
        userDeviceService.bindUserDeviceList(sysUser.getUserNo(),userUpdateDto.getIotIdList());
        return Result.newSuccess();
    }


    private Page<UserResultDto> convertDto(Page<SysUser> sysUserPage) {
        List<SysUser> sysUsers = sysUserPage.getResult();
        Page<UserResultDto> userResultDtoPage = new Page<UserResultDto>();
        BeanUtils.copyProperties(sysUserPage, userResultDtoPage);
        if (sysUsers != null && sysUsers.size() >= 1) {
            for (SysUser sysUser : sysUsers) {
                UserResultDto userResultDto = buildSingleDto(sysUser);
                userResultDtoPage.add(userResultDto);
            }
        }
        return userResultDtoPage;
    }

    private UserResultDto buildSingleDto(SysUser sysUser) {
        UserResultDto userResultDto = new UserResultDto();
        BeanUtils.copyProperties(sysUser, userResultDto);
        userResultDto.setId(sysUser.getId().toString());
        userResultDto.setCreateTime(DateUtil.getDateTimeFormat(sysUser.getCreateTime()));
        userResultDto.setModiTime(DateUtil.getDateTimeFormat(sysUser.getModiTime()));
        userResultDto.setStatus(sysUser.getStatus().toString());
        userResultDto.setStatusName(StatusEnum.getNameByCode(sysUser.getStatus()));
        userResultDto.setIfAdmin(String.valueOf(sysUser.getIfAdmin()));
        userResultDto.setIfAdminName(IfAdminEnum.getNameByCode(sysUser.getIfAdmin()));
        String passWord = ThreeDESUtil.decryptHex(sysUser.getLoginPass());
        userResultDto.setLoginPass(passWord);
        Result<List<UserDeviceRespDto>>  userDeviceRespListResult=userDeviceService.findDbDeviceList(sysUser.getUserNo());
        if(userDeviceRespListResult.isSuccess()){
            List<UserDeviceRespDto> userDeviceRespDtos = userDeviceRespListResult.getData();
            userResultDto.setUserDeviceRespDtos(userDeviceRespDtos);
        }
        return userResultDto;
    }

    private List<SysUser> findList(UserCondDto userCondDto) {
        return sysUserMapper.selectList(userCondDto);
    }
}
